package com.glodon.paas.framework.registry.server.zk.watcher;

import com.glodon.paas.framework.registry.core.type.ClientBasic;
import com.glodon.paas.framework.registry.core.type.ServiceBasic;
import com.glodon.paas.framework.registry.server.zk.util.ZooKeeperServerUtils;
import org.apache.commons.lang.SerializationUtils;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Don Li
 */
public class ClientWatcher implements Watcher {
    private final Logger LOGGER = LoggerFactory.getLogger(ClientWatcher.class);

    private ZooKeeper zk;

    public ClientWatcher(ZooKeeper zk) {
        this.zk = zk;
    }

    @Override
    synchronized public void process(WatchedEvent event) {
        // todo add client watcher for each client
        if (event.getType() == Event.EventType.NodeDataChanged) {
            Stat clientStat = new Stat();
            Stat serviceStat = new Stat();
            try {
                String clientPath = event.getPath();
                ClientBasic clientBasic = (ClientBasic) SerializationUtils.deserialize(zk.getData(clientPath, false, clientStat));
                String servicePath = clientPath.substring(0, clientPath.lastIndexOf('/'));
                ServiceBasic serviceBasic = (ServiceBasic) SerializationUtils.deserialize(zk.getData(servicePath, false, serviceStat));
                switch (clientBasic.getClientStatus()) {
                    case STARTING:
                        break;
                    case UP:
                        /*int num = serviceBasic.getAvailableInstances();
                        if (num == 0) {
                            serviceBasic.setStatus(ServiceStatus.AVAILABLE);
                        }
                        serviceBasic.setAvailableInstances(++num);
                        zk.setData(servicePath, SerializationUtils.serialize(serviceBasic), serviceStat.getVersion());
                        break;*/
                    case DOWN:
                    case OUT_OF_SERVICE:
                        ZooKeeperServerUtils.updateServiceStatus(zk, servicePath);
                        break;
                    default:
                        break;
                }
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } else if (event.getType() == Event.EventType.NodeDeleted) {
            // nothing to do here
        }
    }
}
